<?php

namespace humhub\modules\api\controllers;

use humhub\modules\user\models\User;
use Yii;
use yii\web\HttpException;
use humhub\components\Controller;
use humhub\modules\space\models\Space;
#use humhub\modules\api\models\Space;
use humhub\modules\space\permissions\CreatePublicSpace;
use humhub\modules\space\permissions\CreatePrivateSpace;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 创建一个Space板块
 */
class SpaceCreateController extends BaseController
{

    /**
     * @inheritdoc
     */
    public $modelClass = 'humhub\modules\post\models\Post';

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        $behaviors['acl'] = [
            'class' => \humhub\components\behaviors\AccessControl::className(),
        ];

        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function actions(){
        $actions = parent::actions();
        unset($actions['index'], $actions['view'], $actions['delete'], $actions['update'], $actions['create']);
        return $actions;
    }

    /**
     * 获取指定space数据
     *
     * POST /api/space-create/spaces
     *
     * post.ry_did  融云讨论组id
     *
     * @return  array 指定space数据 username用户名 guid用户guid img用户头像 sguid:space的guid
     */
    public function actionSpaces(){

        $ry_did = Yii::$app->request->post('ry_did');
        $model =Space::findOne(['ry_did' => $ry_did]);
        $uid=$model->created_by;
        $user=User::findOne(['id'=>$uid]);
        $o=[
            'username'=>$user->getDisplayName(),
            'guid'=>$user->guid,
            'img'=>$user->getProfileImage()->getUrl(),
            'sguid'=>$model->guid
        ];


        if( ! $o ){
            throw new \yii\web\BadRequestHttpException('space not found.');
        }
        return $o;

    }

    /**
     * 创建一个Space板块
     *
     * POST /api/space-create/create
     *
     * post.Space[color]  板块颜色,格式:#d1d1d1
     *
     * post.Space[description]  板块描述 (任务介绍)
     *
     * post.Space[join_policy]  加入政策: 0=只能通过邀请(邀请任务), 1=邀请和请求(审批任务), 2=Everyone can enter(自由任务)
     *
     * post.Space[name]   板块名称 (任务主题)
     *
     * post.Space[visibility]  可见性: 1=Public, 0=Private
     *
     * post.Space[s_type]  Space类型：1=任务, 2=课程, 5=院校
     *
     * post.Space[tags]  标签，每个标签以半角逗号( , )分割
     *
     * post.Space[s_t1]     任务开始时间 ->  改为任务报名截止时间
     *
     * post.Space[s_t2]     任务结束时间 ->  改为任务结束时间
     *
     * post.Space[s_img]    任务封面URL
     *
     * post.Space[s_special]  特殊任务标记 bool型 0或1
     *
     * post.Space[s_mode]   任务工作方式 ->  改为任务安排
     *
     * post.Space[s_pg]     新增 -> 作品评估方法
     *
     * post.Space[s_achi]   任务工作成果 ->  改为完成奖励
     *
     * post.Space[s_score]  任务积分奖励
     *
     * post.Space[ry_did] 融云讨论组id
     *
     * @return integer 板块Space的ID; 如果失败data包含错误原因,需遍历data显示对应的错误
     */
    public function actionCreate(){
        // User cannot create spaces (public or private)
        // 如果创建的Space在web端无法访问，是因为 table:contentcontainer 的class:
        // 存入的是:humhub\modules\api\models\Space
        // 实际应是:humhub\modules\space\models\Space
        //use humhub\modules\space\models\Space;
        //#use humhub\modules\api\models\Space;
        if (!Yii::$app->user->permissionmanager->can(new CreatePublicSpace) && !Yii::$app->user->permissionmanager->can(new CreatePrivateSpace)) {
            throw new HttpException(400, '没有权限创建板块');
        }

        $space = Yii::$app->request->post('Space');
        $s_type = $space['s_type'];
        if( $s_type!=1 ){
            throw new HttpException(400, 's_type error.');
        }

        $model = $this->createSpaceModel();
        $model->ry_did=$space['ry_did'];
        if (isset($space['s_special'])){
            $model->s_special=$space['s_special'];
        }else{
            $model->s_special= 0;
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return array(
                'sguid' => $model->guid,
            );
            //return $model->id;
            //邀请流程
            //return $this->actionModules($model->id);
        }else{
            Yii::$app->params['res-success'] = false;
            return $model->getErrors();
        }
    }

    /**
     * 编辑一个Space板块
     *
     * PUT /api/space-create/edit
     *
     * post.Space[guid]  Space的guid
     *
     * 其他参数同接口:创建Space
     */
    public function actionEdit(){
        $space = Yii::$app->request->post('Space');

        $guid = $space['guid'];
        $model = Space::findOne(['guid' => $guid]);
        if( ! $model ){
            throw new \yii\web\BadRequestHttpException('Task not found.');
        }
        if( (time() - strtotime($model->created_at)) > 600 ){
            throw new \yii\web\BadRequestHttpException('任务编辑时间已过.');
        }

        if( Yii::$app->user->id != $model->created_by ){
            throw new HttpException(400, '没有权限创建板块');
        }

        $s_type = $space['s_type'];
        if( $s_type!=1 ){
            throw new HttpException(400, 's_type error.');
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return array(
                'sguid' => $model->guid,
            );
            //return $model->id;
            //邀请流程
            //return $this->actionModules($model->id);
        }else{
            Yii::$app->params['res-success'] = false;
            return $model->getErrors();
        }
    }

    /**
     * @inheritdoc
     */
    protected function createSpaceModel()
    {
        $model = new Space();
        $model->scenario = 'create';
        $model->visibility = Yii::$app->getModule('space')->settings->get('defaultVisibility');
        $model->join_policy = Yii::$app->getModule('space')->settings->get('defaultJoinPolicy');
        return $model;
    }
}
?>
